package com.cxl.harmony.fingerguessing;

import com.cxl.harmony.fingerguessing.utils.CommonData;
import com.cxl.harmony.fingerguessing.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.*;

public class FingerGuessingServiceAbility extends Ability {
    private static final String TAG = CommonData.TAG + FingerGuessingServiceAbility.class.getSimpleName();

    private MathRemote remote = new MathRemote();

    @Override
    public void onStart(Intent intent) {
        LogUtil.info(TAG, "RemoteServiceAbility::onStart");
        super.onStart(intent);
    }

    @Override
    protected void onCommand(Intent intent, boolean restart, int startId) {
        LogUtil.info(TAG, "RemoteServiceAbility::onCommand");
        super.onCommand(intent, restart, startId);
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.info(TAG, "RemoteServiceAbility::onStop");
    }

    @Override
    protected IRemoteObject onConnect(Intent intent) {
        super.onConnect(intent);
        return remote.asObject();
    }

    private void sendEvent(int otherFinger) {
        LogUtil.info(TAG, "sendEvent......");
        try {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder().withAction(CommonData.FINGERGUESSING_EVENT).build();
            intent.setOperation(operation);
            intent.setParam(CommonData.KEY_FINGER, otherFinger);
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventManager.publishCommonEvent(eventData);
        } catch (RemoteException e) {
            LogUtil.error(TAG, "publishCommonEvent occur exception.");
        }
    }

    /**
     * MathRemote Establish a remote connection
     */
    public class MathRemote extends RemoteObject implements IRemoteBroker {
        private static final int ERR_OK = 0;

        private MathRemote() {
            super("MathRemote");
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            LogUtil.info(TAG, "onRemoteRequest......");
            int otherFinger = data.readInt();
            reply.writeInt(ERR_OK);
            sendEvent(otherFinger);
            return true;
        }
    }
}